import { Component, director, game } from "cc"
import { createUINode } from "../Utils"
import { EVENT_ENUM, SHAKE_TYPE } from "../Enum"
import { EventManager } from "./EventManager"

export class ShakeManager extends Component{

    private beginTime: number = 0   //ms
    private isShakeing: boolean = false
    private oldPos: { x: number; y: number } = { x: 0, y: 0 }
    private shakeType: SHAKE_TYPE

    protected onLoad(): void {
        EventManager.getInstance().on(EVENT_ENUM.SHAKE, this.onShake, this)
    }

    protected onDestroy(): void {
        EventManager.getInstance().off(EVENT_ENUM.SHAKE, this.onShake)
    }

    onShake(type: SHAKE_TYPE){
        if(this.isShakeing){
            return
        }
        this.isShakeing = true
        this.beginTime = game.totalTime
        this.oldPos.x = this.node.position.x
        this.oldPos.y = this.node.position.y
        this.shakeType = type
    }

    update(){
        if (this.isShakeing){
            this.shake()
        }
    }

    shake(){
        //振幅
        const shakeAmount = 1.6
        //持续时间
        const duration = 200
        //频率
        const frequency = 12
        //当前时间
        const curSecond = (game.totalTime - this.beginTime) / 1000
        //总时间
        const totalSecond = duration / 1000
        const offset = shakeAmount * Math.sin(frequency * Math.PI * curSecond)
        if (this.shakeType === SHAKE_TYPE.TOP) {
            this.node.setPosition(this.oldPos.x, this.oldPos.y - offset)
        } else if (this.shakeType === SHAKE_TYPE.BOTTOM) {
            this.node.setPosition(this.oldPos.x, this.oldPos.y + offset)
        } else if (this.shakeType === SHAKE_TYPE.LEFT) {
            this.node.setPosition(this.oldPos.x - offset, this.oldPos.y)
        } else if (this.shakeType === SHAKE_TYPE.RIGHT) {
            this.node.setPosition(this.oldPos.x + offset, this.oldPos.y)
        }
        if (curSecond > totalSecond) {
            this.isShakeing = false
            this.node.setPosition(this.oldPos.x, this.oldPos.y)
        }
    }

}